package com.bdqn.web;

import com.bdqn.utils.UuidUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        System.out.println(type);
        try{
            if("up".equals(type)){
                upServlet(request,response);
            }else if("down".equals(type)){
                downServlet(request,response);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void downServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setContentType("text/json;charset=utf-8");
        String path = (String) request.getServletContext().getAttribute("path");

        response.getWriter().write(path);

    }

    private void upServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        //判断文件是否是上传操作  enctype="multipart/form-data">
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);

            //创建一个标记位,标记当前有上传文件的操作  type="file"
            boolean flag = false;
            for (FileItem item : fileItems) {
                if (null != item.getName()) {
                    flag = true;
                    break;
                }
            }
            //如果有，使用uuid给改图片生成一个唯一的地址//32 |  64
            String pictureId = UuidUtil.getUuid()+".jpg";
            // --处理form表单提交过来的文件数据
            for (FileItem item : fileItems) {
                //5.当前表单是否是文件表单 type="file"
                if (!item.isFormField()) {
                    //写到一个目录
                    //6.从临时存储文件的地方将内容写入到指定位置
                    File upload = new File(this.getServletContext().getRealPath("upload"), pictureId);
                    //获取当前图片的虚拟路径，如果是存绝对路径，img的src获取不到
                    String path=request.getContextPath()+"/upload/"+pictureId;
                    System.out.println(path);
                    item.write(upload);

                    //将 /exam_project/upload/fc5cca22dd1549a4b60164a08c8fd361.jpg 保存到数据库
                    //
                    //
                    request.getServletContext().setAttribute("path",path);
                }
            }
            //如果有缓存就用转发，没有就用重定向也行
            response.sendRedirect(request.getContextPath() + "/upload.html");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
